from rest_framework import serializers
from pet.models import *

class PetSerializer(serializers.ModelSerializer):
    gender = serializers.ChoiceField(choices=[(0, '雄性'), (1, '雌性')])
    species_name = serializers.CharField(write_only=True, required=False)  # 物种名称字段可选
    species = serializers.PrimaryKeyRelatedField(queryset=SpeciesModel.objects.all(), required=False)  # 物种 ID 字段可选

    class Meta:
        model = PetModel
        fields = '__all__'

    def create(self, validated_data):
        species_name = validated_data.pop('species_name', None)

        # 如果传递了 species_name，通过名称查找物种并赋值
        if species_name:
            species = SpeciesModel.objects.filter(species=species_name).first()
            if species is None:
                raise serializers.ValidationError(f"物种 '{species_name}' 不存在。")
            validated_data['species'] = species
        # 如果没有传递 species_name，确保通过 species 外键 ID 传递物种
        elif 'species' not in validated_data:
            raise serializers.ValidationError("物种信息是必填的。")

        return super().create(validated_data)